package top.mhtools.pigeon.ding.service.support;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import top.mhtools.pigeon.common.enums.DingMessageTypeEnum;
import top.mhtools.pigeon.common.persistence.DingRequest;
import top.mhtools.pigeon.ding.dto.DingMessageReqDTO;
import top.mhtools.pigeon.template.dto.DingTemplateRespDTO;
import top.mhtools.pigeon.template.dto.TemplateReqDTO;
import top.mhtools.pigeon.template.service.TemplateService;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * MD消息发送器
 *
 * @author machen
 * @date 2020/4/24 19:34
 */
@Slf4j
@Component
public class DingMessageMdSolver extends AbstractDingMessageExecuteStrategy {

    @Resource(name = "dingTemplateServiceImpl")
    private TemplateService templateService;

    private static final Pattern pattern = Pattern.compile("@(.*?)@");

    @Override
    public void execute(DingRequest dingRequest) {
        String serverUrl = dingtalkUrl + "?access_token=" + dingRequest.getToken();
        List<String> atList = dingRequest.getAtMobiles();
        DingMessageReqDTO.Markdown messageReqDTO = dingRequest.getMarkdown();

        // 指定消息类型
        DingTalkClient client = new DefaultDingTalkClient(serverUrl);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype(DingMessageTypeEnum.MD.getName());

        String titleStr = "";
        String markStr = "";

        if (StringUtils.isNotEmpty(dingRequest.getTemplateId())) {
            DingTemplateRespDTO template = (DingTemplateRespDTO) templateService.getTemplate(new TemplateReqDTO(dingRequest.getTemplateId()));
            String contentTemplateStr = template.getContent();

            Map<String, Object> params = messageReqDTO.getTextMap();

            if (CollectionUtil.isNotEmpty(atList)) {
                request.setAt(buildAt(atList));
                String atStr = atList.stream().map(each -> each = "@" + each).collect(Collectors.joining(" "));
                params.put("at", atStr);
            }

            Matcher matcher = pattern.matcher(contentTemplateStr);
            while (matcher.find()) {
                // 占位符
                String placeholder = matcher.group();
                String key = placeholder.substring(1, placeholder.length() - 1);
                if (params.containsKey(key)) {
                    String value = params.get(key).toString().trim();
                    contentTemplateStr = StringUtils.replace(contentTemplateStr, placeholder, value);
                }
            }

            markStr = Arrays.stream(StrUtil.split(contentTemplateStr, "&")).collect(Collectors.joining("\n\n"));
            titleStr = template.getTemplateName();
        } else {
            if (CollectionUtil.isNotEmpty(atList)) {
                request.setAt(buildAt(atList));
            }
            markStr = messageReqDTO.getText();
            titleStr = messageReqDTO.getTitle();
        }

        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
        markdown.setTitle(titleStr);

        markdown.setText(markStr);
        request.setMarkdown(markdown);

        sendMessage(client, request);
    }

    @Override
    public String supports() {
        return DingMessageTypeEnum.MD.getName();
    }
}
